package com.yuqiangz.sync;

/**
 * @author 赵雨强
 * @create 2021/7/10 14:10
 * @description synchronized实现线程之间通信
 */
public class ThreadDemo1 {
    public static void main(String[] args) {
        Share share = new Share();
        //创建线程
        new Thread(()->{
            for (int i = 1; i <=10; i++) {
                share.incr(); //+1
            }
        },"AA").start();

        new Thread(()->{
            for (int i = 1; i <=10; i++) {
                share.decr(); //-1
            }
        },"BB").start();

        new Thread(()->{
            for (int i = 1; i <=10; i++) {
                share.incr(); //+1
            }
        },"CC").start();

        new Thread(()->{
            for (int i = 1; i <=10; i++) {
                share.decr(); //-1
            }
        },"DD").start();
    }
}


class Share {
    private int number = 0;
    public synchronized void incr(){
        while (number != 0){
            try {
                // 在哪里睡的，就在哪里醒，所以使用while
                // wait方法会立即释放锁
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        number++;
        System.out.println(Thread.currentThread().getName()+" :: "+number);
        this.notifyAll();
    }

    public synchronized void decr(){
        while (number != 1){
            try {
                // 在哪里睡的，就在哪里醒，所以使用while
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        number--;
        System.out.println(Thread.currentThread().getName()+" :: "+number);
        this.notifyAll();
    }
}
